package com.github.springboot.controller;

import com.alibaba.druid.util.StringUtils;
import com.github.springboot.common.Response;
import com.sun.corba.se.spi.resolver.LocalResolver;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * Created by kjtang on 2018/1/19.
 *  国际化实现语言切换
 */
@Api("国际化操作相关的API")
@RestController("/api/il8n")
public class IL8NController {


    @ApiOperation(value = "切换语言",notes = "切换语言",httpMethod = "GET")
    @ApiResponses({
            @ApiResponse(code=200,message = "语言切换成功"),
            @ApiResponse(code=500,message = "语言切换成功")
    })
    @RequestMapping(value="/language/{lan}",method=RequestMethod.GET)
    public Response language(@PathVariable("lan") String lan , HttpServletRequest request, HttpServletResponse response) throws Exception{
        Response resp = new Response(Response.SUCCESS);
        //实现国际化语言切换
        LocaleResolver  localeResolver = RequestContextUtils.getLocaleResolver(request);
        if(!StringUtils.isEmpty(lan)){
            String language = lan.toLowerCase();
            if(language.equals("zh_cn")){
                localeResolver.setLocale(request, response, Locale.CHINA);
            }else if(language.equals("en")){
                localeResolver.setLocale(request, response, Locale.US);
            }else{
                localeResolver.setLocale(request, response, Locale.CHINA );
            }
        }else{
            localeResolver.setLocale(request, response, Locale.CHINA );
        }
        return resp;
    }

}
